﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Xsl;
using System.IO;
using System.Net;
using Microsoft.SharePoint;

namespace SCCL2010
{
    public class TextFunctions
    {


        /// <summary>
        /// Method for retrieving email text.
        /// </summary>
        /// <param name="cKey"></param>
        /// <param name="item"></param>
        /// <returns>returns a string representing the EmailText.</returns>
        public static string GetEmailText(string cKey, SPListItem item)
        {
            string cOutStr = "";
            try
            {
                cOutStr = Config.ReadConfigValue(item.Web, cKey);
                cOutStr = TextFunctions.TransformText(item, cOutStr);
            }
            catch (Exception ex)
            {
                ErrorHandling.HandleError(item.Web, "GetEmailText", ex);
            }
            return cOutStr;
        }


        /// <summary>
        /// Transforms the input string based on the TextWorkType.
        /// </summary>
        /// <param name="item"></param>
        /// <param name="cWorkText"></param>
        /// <returns>returns a transformed string based on the WorkText.</returns>
        public static string TransformText(SPListItem item, string cWorkText)
        {
            TextWorkType oTextType = new TextWorkType();
            if (cWorkText.ToLower().Contains("xsl:stylesheet"))
            {
                oTextType = TextWorkType.XSLT;
            }
            else if (cWorkText.Contains("[["))
            {
                oTextType = TextWorkType.TextReplace;
            }
            else oTextType = TextWorkType.PlainText;

            string cRetVal = "";

            switch (oTextType)
            {
                case TextWorkType.XSLT:
                    cRetVal = RenderXSL(cWorkText, item.Xml);
                    break;
                case TextWorkType.TextReplace:
                    cRetVal = ReplaceItemText(item, cWorkText);
                    break;
                default:
                    cRetVal = cWorkText;
                    break;
            }
            return cRetVal;
        }

        /// <summary>
        /// Method for formatting the SPFieldType of the item.
        /// </summary>
        /// <param name="item"></param>
        /// <param name="cWorkText"></param>
        /// <returns>returns the formatted string based on the WorkText.</returns>
        private static string ReplaceItemText(SPListItem item, string cWorkText)
        {
            if (cWorkText.ToLower().Contains("[[parentlistid]]"))
            {
                cWorkText = cWorkText.Replace("[[parentlistid]]", item.ParentList.ID.ToString());
            }
            if (cWorkText.ToLower().Contains("[[currentweburl]]"))
            {
                cWorkText = cWorkText.Replace("[[currentweburl]]", item.ParentList.ParentWeb.Url.ToString());
            }

            foreach (SPField fld in item.Fields)
            {
                string cFieldMaker = String.Format("[[{0}]]", fld.Title);
                if (cWorkText.Contains(cFieldMaker))
                {
                    string cTextValue = "";
                    switch (fld.Type)
                    {
                        case SPFieldType.Currency:
                            break;
                        case SPFieldType.DateTime:
                            try
                            {
                                if (item != null)
                                {
                                    if (fld != null)
                                    {
                                        if (item[fld.Title] != null)
                                        {
                                            SPFieldDateTime fDT = (SPFieldDateTime)fld;
                                            if (fDT.DisplayFormat == SPDateTimeFieldFormatType.DateOnly)
                                            {
                                                cTextValue = Convert.ToDateTime(item[fld.Title].ToString()).ToShortDateString();
                                            }
                                            else
                                            {
                                                cTextValue = item[fld.Title].ToString();
                                            }
                                        }
                                    }
                                }

                            }
                            catch (Exception ex)
                            {
                                ErrorHandling.HandleError(item.ParentList.ParentWeb, "ReplaceItemText", ex);
                            }
                            break;
                        case SPFieldType.Lookup:
                            try
                            {

                                if (item != null)
                                {
                                    if (fld != null)
                                    {
                                        if (item[fld.Title] != null)
                                            cTextValue = item[fld.Title].ToString();
                                    }
                                }

                            }
                            catch (Exception ex)
                            {
                                ErrorHandling.HandleError(item.ParentList.ParentWeb, "ReplaceItemText", ex);
                            }
                            break;
                        case SPFieldType.User:

                            try
                            {

                                if (item != null)
                                {
                                    if (fld != null)
                                    {
                                        if (item[fld.Title] != null)
                                        {
                                            SPFieldUserValue oUser = new SPFieldUserValue(item.Web, item[fld.Title].ToString());
                                            cTextValue = oUser.User.LoginName;
                                        }

                                    }
                                }

                            }
                            catch (Exception ex)
                            {
                                ErrorHandling.HandleError(item.ParentList.ParentWeb, "ReplaceItemText", ex);
                            }
                            break;
                        default:
                            try
                            {

                                if (item != null)
                                {
                                    if (fld != null)
                                    {
                                        if (item[fld.Title] != null)
                                            cTextValue = item[fld.Title].ToString();
                                    }
                                }

                            }
                            catch (Exception ex)
                            {
                                ErrorHandling.HandleError(item.ParentList.ParentWeb, "ReplaceItemText", ex);
                            }
                            break;
                        //case SPFieldType.Invalid:
                        //case SPFieldType.Integer:
                        //case SPFieldType.Text:
                        //case SPFieldType.Note:
                        //case SPFieldType.Counter:
                        //case SPFieldType.Choice:
                        //case SPFieldType.Boolean:
                        //case SPFieldType.Number:
                        //case SPFieldType.URL:
                        //case SPFieldType.Computed:
                        //case SPFieldType.Threading:
                        //case SPFieldType.Guid:
                        //case SPFieldType.MultiChoice:
                        //case SPFieldType.GridChoice:
                        //case SPFieldType.Calculated:
                        //case SPFieldType.File:
                        //case SPFieldType.Attachments:
                        //case SPFieldType.Recurrence:
                        //case SPFieldType.CrossProjectLink:
                        //case SPFieldType.ModStat:
                        //case SPFieldType.Error:
                        //case SPFieldType.ContentTypeId:
                        //case SPFieldType.PageSeparator:
                        //case SPFieldType.ThreadIndex:
                        //case SPFieldType.WorkflowStatus:
                        //case SPFieldType.AllDayEvent:
                        //case SPFieldType.WorkflowEventType:
                        //case SPFieldType.MaxItems:
                        //    break;
                    }



                    cWorkText = cWorkText.Replace(cFieldMaker, cTextValue);
                }
            }
            return cWorkText;
        }

        /// <summary>
        /// Transforms the XML generated by getting the list items
        /// </summary>
        /// <param name="cXSL"></param>
        /// <param name="cXML"></param>
        /// <returns></returns>
        public static string RenderXSL(string cXSL, string cXML)
        {
            string cHTML = "";
            try
            {
                ASCIIEncoding oEncode = new ASCIIEncoding();
                //using (Stream xmlstream = new MemoryStream(oEncode.GetBytes(cXML)))
                //{
                //    //using (Stream xslstream = new MemoryStream(oEncode.GetBytes(cXSL)))
                //    //{
                //    //    //cHTML = GetTransformResults(xslstream, xmlstream);
                //    //}
                //}
            }
            catch (Exception exc)
            {
                ErrorHandling.HandleError("RenderXSL", exc);
            }
            return cHTML;
        }

        /// <summary>
        ///  Performs the actual transformation of the document from XML to HTML.
        /// </summary>
        /// <param name="xslstream"></param>
        /// <param name="responseStream"></param>
        /// <returns></returns>
        public static string GetTransformResults(Stream xslstream, Stream responseStream)
        {
            XmlUrlResolver resolver = new XmlUrlResolver { Credentials = CredentialCache.DefaultCredentials };
            using (XmlTextReader stylesheet = new XmlTextReader(xslstream))
            {
                stylesheet.XmlResolver = resolver;
                XslCompiledTransform transform = new XslCompiledTransform();
                XsltSettings oSettings = new XsltSettings { EnableScript = true };
                transform.Load(stylesheet, oSettings, null);
                StringBuilder sb = new StringBuilder();
                using (TextWriter writer = new StringWriter(sb))
                {
                    using (XmlReader reader = new XmlTextReader(responseStream))
                    {
                        using (XmlTextWriter results = new XmlTextWriter(writer))
                        {
                            transform.Transform(reader, results);
                        }
                        reader.Close();
                    }
                }
                return sb.ToString();
            }
        }
    }
}
